using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

namespace ZhiSe.Editor
{
    public class SeegBuild : IPreprocessBuildWithReport, IPostprocessBuildWithReport
    {
        public static string OutputPath = "";
        
        public int callbackOrder { get; }

#if UNITY_ANDROID
        private static readonly string[] NeedPfList = new string[] { "hgg" };
#elif UNITY_IOS
        private static readonly string[] NeedPfList = new string[] { "hios" };
#elif MINIGAME_SUBPLATFORM_WEIXIN
        private static readonly string[] NeedPfList = new string[] { "wx" };
#elif MINIGAME_SUBPLATFORM_DOUYIN
        private static readonly string[] NeedPfList = new string[] { "tt" };
#elif MINIGAME_SUBPLATFORM_KUAISHOU
        private static readonly string[] NeedPfList = new string[] { "ks" };
#elif UNITY_WEBGL
        private static readonly string[] NeedPfList = new string[] { "wx", "tt", "ks" };
#else
        private static readonly string[] NeedPfList = null;
#endif

        public void OnPreprocessBuild(BuildReport report)
        {
            // 删除缓存的资源
            _preDelete();
#if UNITY_WEBGL || MINIGAME_SUBPLATFORM_DOUYIN
            System.Environment.SetEnvironmentVariable("PYTHONUTF8", "1");
#if SEEG_PF_TT
            // 抖音的js脚本注入没有钩子，写入脚本
            var jsDir = Path.Combine(Application.dataPath, "StreamingAssets/__cp_js_files");
            if (!Directory.Exists(jsDir))
            {
                Directory.CreateDirectory(jsDir);
            }
            var cfg = SeegUtil.GetSdkCfg();
            // 移动td.js
            var tdJsPath = Path.Combine(Path.GetFullPath("Packages/com.seeg.sdk"), "Editor", "Res", "td.js");
            if (File.Exists(tdJsPath) && !string.IsNullOrEmpty(cfg.Value<string>("tdAppKey")))
            {
                File.Copy(tdJsPath, Path.Combine(jsDir, "td.js"), true);
            }
            // 设置参数
            File.WriteAllText(Path.Combine(jsDir, "seeg.js"), $"const zsSdkConfig = {cfg};\nGameGlobal.zs = GameGlobal.zs || {{}};\nGameGlobal.zs.gameConfig = zsSdkConfig;");
#endif
#endif
        }

        private static void _preDelete()
        {
            var jsDir = Path.Combine(Application.dataPath, "StreamingAssets/__cp_js_files");
            if (!Directory.Exists(jsDir))
            {
                return;
            }

            var tdJsPath = Path.Combine(jsDir, "td.js");
            if (File.Exists(tdJsPath))
            {
                File.Delete(tdJsPath);
            }
            var tdMetaPath = Path.Combine(jsDir, "td.js.meta");
            if (File.Exists(tdMetaPath))
            {
                File.Delete(tdMetaPath);
            }
            
            var seegJsPath = Path.Combine(jsDir, "seeg.js");
            if (File.Exists(seegJsPath))
            {
                File.Delete(seegJsPath);
            }

            var seegMetaPath = Path.Combine(jsDir, "seeg.js.meta");
            if (File.Exists(seegMetaPath))
            {
                File.Delete(seegMetaPath);
            }
        }
        
        public void OnPostprocessBuild(BuildReport report)
        {
            if (null == NeedPfList)
            {
                Debug.LogError("[SEEG] SDK暂不支持当前渠道");
                return;
            }

            var cfg = SeegUtil.GetSdkCfg();
            if (null == cfg)
            {
                Debug.LogError("[SEEG] 未选择构建配置");
                return;
            }
            var gid = (string)cfg["gid"];

            Debug.LogWarning($"[SEEG] 请确认构建的GID为 {gid}");
            
            if (string.IsNullOrEmpty(gid))
            {
                Debug.LogError("[SEEG] GID不能为空");
                return;
            }
            var pf = gid.Split("_")[0];
            Debug.Log($"[SEEG] ===Seeg运行开始===\n您选择的渠道是：{pf}");
            
            if (!NeedPfList.Contains(pf))
            {
                Debug.LogError("[SEEG] 当前的gid与渠道不对应");
                return;
            }
            
            OutputPath = report.summary.outputPath;
            
            switch (report.summary.platform)
            {
#if TUANJIE_1_0_OR_NEWER
                case BuildTarget.MiniGame:
#if SEEG_PF_KS
                _ = SeegKSBuild.afterBuildTemplate(cfg);
#endif
                    break;
#endif
                case BuildTarget.WebGL:
#if UNITY_WEBGL
                    SeegWebGLBuild.AfterBuildTemplate(cfg);
#if SEEG_PF_KS
                    _ = SeegKSBuild.afterBuildTemplate(cfg);
#endif
#endif
                    break;
                case BuildTarget.Android:
#if UNITY_ANDROID
                    SeegAndroidBuild.OnPostprocessBuild(gid, pf, cfg);
#endif
                    break;
                case BuildTarget.iOS:
#if UNITY_IOS
                    SeegIOSBuild.OnPostprocessBuild(gid, pf, cfg);
#endif
                    break;
                default:
                    Debug.Log("[SEEG] 不支持的平台");
                    return;
            }
            
            Debug.Log("[SEEG] ===Seeg运行结束===");
        }
    }
}